package retrofit;

import java.util.concurrent.TimeUnit;

import bean.MSGResult;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by chinalin on 2017/4/19.
 */

public class HttpMethods {

    public static final String BASE_URL = "http://192.168.2.156:8080";
//    public static final String BASE_URL = "http://192.168.1.103:8080";

    private static final int DEFAULT_TIMEOUT = 5;

    private Retrofit retrofit;
    private RequestSerives requestSerives;

    //构造方法私有
    private HttpMethods() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        //retrofit已经把Json解析封装在内部了 你需要传入你想要的解析工具就行了 默认支持Gson解析
        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)                    //服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(new OkHttpClient()).build();

        requestSerives = retrofit.create(RequestSerives.class);
    }

    //在访问HttpMethods时创建单例
    private static class SingletonHolder{
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    //获取单例
    public static HttpMethods getInstance(){
        return SingletonHolder.INSTANCE;
    }

    //进行网络请求
    public void getMsg(Subscriber<String> subscriber,String url,int type,int ver){
//        requestSerives.getCheckVer("/serverapi/checkver/bootver",691,0)
        Observable observable =requestSerives.getCheckVer(url,type,ver)
                        .map(new HttpResultFunc<String>());
        toSubscribe(observable,subscriber);
    }

    //添加线程管理并订阅
    @SuppressWarnings("unchecked")
    private void toSubscribe(Observable o, Subscriber s){
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    private class HttpResultFunc<T> implements Func1<MSGResult<T>, T> {

        @Override
        public T call(MSGResult<T> tmsgResult) {
            if (tmsgResult.getResultCode() != 0) {
                throw new RuntimeException("回复的代码：" + tmsgResult.getResultCode());
//                throw new ApiException(tmsgResult.getResultCode());
            }
            return tmsgResult.getData();
        }
    }
}
